// utils/ref/struct_to_map.go
package ref

import (
	"errors"
	"reflect"
)

func StructToMapByMaps(val any) (mps map[string]any, err error) {
	mps = make(map[string]any)
	v := reflect.ValueOf(val)
	t := reflect.TypeOf(val)
	// 可以去判断它的类型，只能是结构体
	if t.Kind() != reflect.Struct {
		err = errors.New("只能接收结构体参数")
		return
	}

	for i := 0; i < v.NumField(); i++ {
		f := v.Field(i)
		switch f.Kind() {
		case reflect.Ptr:
			if f.IsNil() {
				continue
			}
			if f.Elem().IsZero() {
				continue
			}
			tag := t.Field(i).Tag.Get("json")
			if tag == "" || tag == "-" {
				continue
			}
			mps[tag] = f.Elem().Interface()
		}
	}
	return
}
